package cn.wolfcode.service.impl;

import cn.wolfcode.Condition;
import cn.wolfcode.common.exception.BusinessException;
import cn.wolfcode.common.web.CodeMsg;
import cn.wolfcode.domain.OrderInfo;
import cn.wolfcode.domain.Product;
import cn.wolfcode.mapper.ProductMapper;
import cn.wolfcode.service.IProductService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.Date;
import java.util.List;


@Service
public class ProductServiceImpl implements IProductService {
    private final ProductMapper productMapper;

    public ProductServiceImpl(ProductMapper productMapper) {
        this.productMapper = productMapper;
    }

    @Override
    public List<Product> selectByIdList(List<Long> idList) {
        return productMapper.queryProductByIds(idList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addOrder(OrderInfo orderInfo) {
        int row = productMapper.stockById(orderInfo);
        if(row <= 0){
            throw new BusinessException(new CodeMsg(500,"库存不足"));
        }
        orderInfo.setStatus(OrderInfo.STATUS_ARREARAGE);
        orderInfo.setCreateDate(new Date());
        productMapper.addOrder(orderInfo);
    }

    @Override
    public List<Product> findAll() {
        return productMapper.findAll();
    }

    @Override
    public PageInfo<OrderInfo> conditionFindByPage(Integer page, Integer pageSize, Condition condition) {
        PageHelper.startPage(page, pageSize);
        return new PageInfo<>(productMapper.conditionFindByPage(page, pageSize, condition));
    }

    @Override
    public void updateOrder(OrderInfo orderInfo) {
        productMapper.updateOrder(orderInfo);
    }

    @Override
    public void batchDeleteOrder(List<Long> ids) {
        productMapper.batchDeleteOrder(ids);
    }

    @Override
    public Product findById(Long id) {
        return productMapper.findById(id);
    }
}
